package com.example.friend.service.impl;


import com.example.core.domain.TableDataInfo;
import com.example.core.utils.StringUtils;
import com.example.friend.domain.dto.QuestionSearchDTO;
import com.example.friend.domain.vo.QuestionESVO;
import com.example.friend.domain.vo.QuestionVO;
import com.example.friend.elasticsearch.QuestionRepository;
import com.example.friend.manger.QuestionCacheManager;
import com.example.friend.service.IQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class QuestionServiceImpl implements IQuestionService {

    @Autowired
    private QuestionCacheManager questionCacheManager;

    @Autowired
    private QuestionRepository questionRepository;

    @Override
    public TableDataInfo selectQuestionList(QuestionSearchDTO searchDTO) {
        if (!StringUtils.isEmpty(searchDTO.getKeyword())) {
            return search(searchDTO);
        }

        //分页参数
        int start = (searchDTO.getPageNum() - 1) * searchDTO.getPageSize();
        int end = start + searchDTO.getPageSize();

        if (searchDTO.getDifficulty() != null) {
            return questionCacheManager.selectQuestionListByDifficult(questionRepository, searchDTO.getDifficulty(), start, end);
        }
        return questionCacheManager.selectQuestionList(questionRepository, start, end);
    }

    @Override
    public List<QuestionVO> selectHotQuestionList() {
        return questionCacheManager.selectHotQuestionList(questionRepository);
    }

    @Override
    public TableDataInfo search(QuestionSearchDTO searchDTO) {
        Pageable pageable = PageRequest.of(searchDTO.getPageNum() - 1, searchDTO.getPageSize());
        String keyword = "%" + searchDTO.getKeyword() + "%";
        Integer difficulty = searchDTO.getDifficulty();
        Page<QuestionESVO> questionByTitleOrContent =
                questionRepository.findQuestionByTitleOrContentAndDifficulty(keyword, keyword, difficulty, pageable);
        TableDataInfo info = TableDataInfo.empty();
        long totalElements = questionByTitleOrContent.getTotalElements();
        if (totalElements == 0) {
            return info;
        }
        info.setTotal(totalElements);
        info.setRows(questionByTitleOrContent.getContent());
        return info;
    }

    @Override
    public QuestionESVO detail(Long questionId) {
        return questionCacheManager.detail(questionRepository, questionId);
    }

    @Override
    public Long preQuestion(Long questionId) {
        return questionCacheManager.preQuestion(questionId);
    }

    @Override
    public Long nextQuestion(Long questionId) {
        return questionCacheManager.nextQuestion(questionId);
    }
}
